package com.loong.factory.utils;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class SubmodulePathFinderUtil {

    /**
     * 获取当前子模块的绝对路径
     * @return 子模块的绝对路径
     * @throws IOException 如果发生IO异常
     */
    public static String getSubmodulePath() throws IOException {
        try {
            // 获取当前类的类加载器
            ClassLoader classLoader = SubmodulePathFinderUtil.class.getClassLoader();
            if (classLoader == null) {
                throw new IOException("无法获取类加载器");
            }

            // 获取当前类的路径
            String resourcePath = Objects.requireNonNull(classLoader.getResource(""), "资源路径为空").getPath();

            // 解码路径
            String decodedPath = URLDecoder.decode(resourcePath, StandardCharsets.UTF_8);

            // 转换为文件路径并标准化
            File directory = new File(decodedPath);
            String courseFile = directory.toPath().normalize().toString();

            // 标准化路径分隔符
            String standardizedPath = standardizePath(courseFile);
            String removeString = "out/production/";
            standardizedPath = standardizedPath.replace(removeString, "");
            return standardizedPath;
        } catch (Exception e) {
            throw new IOException("获取子模块路径时发生错误: " + e.getMessage(), e);
        }
    }

    /**
     * 标准化路径分隔符
     * @param path 原始路径
     * @return 标准化后的路径
     */
    private static String standardizePath(String path) {
        return path.replace(File.separator.equals("\\") ? "\\" : "/", "/");
    }
}
